﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketWinFormHelloWorld
{
    public partial class Server : Form
    {
        int sum = 0;
        Socket socket;
        public Server()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            listInfo.Items.Add("========开始监听消息========");
            try
            {
                if (chkIsAsync.Checked)//异步
                {
                    IPEndPoint iep = new IPEndPoint(IPAddress.Any, String.IsNullOrEmpty(txtPort.Text) ? 50000 : Convert.ToInt32(txtPort.Text));
                    byte[] receiveData = new byte[1024];
                    socket = null;
                    if (radTCP.Checked)
                    {
                        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    }
                    else if (radUDP.Checked)
                    {
                        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    }
                    socket.Bind(iep);

                    SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
                    arg.RemoteEndPoint = iep;
                    arg.SetBuffer(receiveData, 0, receiveData.Length);
                    arg.Completed += (s, args) =>
                    {
                        if (args.SocketError == SocketError.Success)
                        {
                            string result = Encoding.UTF8.GetString(receiveData, 0, args.BytesTransferred);
                            if (listInfo.InvokeRequired)
                            {
                                listInfo.Invoke(new MethodInvoker(() =>
                                {
                                    listInfo.Items.Add(result);
                                    listInfo.SelectedIndex = listInfo.Items.Count - 1;
                                }));
                            }
                            socket.ReceiveFromAsync(arg);
                        }
                        else
                        {
                            if (listInfo.InvokeRequired)
                            {
                                listInfo.Invoke(new MethodInvoker(() =>
                                {
                                    listInfo.Items.Add(arg.SocketError.ToString());
                                    listInfo.SelectedIndex = listInfo.Items.Count - 1;
                                }));
                            }
                        }
                    };
                    socket.ReceiveFromAsync(arg);
                }
                else//同步
                {
                    if (!taskListener.IsBusy)
                    {
                        taskListener.RunWorkerAsync();
                    }
                }
                StartOrEnd(true);
            }
            catch
            {
            }
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            if (chkIsAsync.Checked)
            {
                //socket.Close();
                //listInfo.Items.Add("========监听终止========");
            }
            else
            {
                if (taskListener.IsBusy)
                {
                    taskListener.CancelAsync();
                }
            }
            socket.Close();
            listInfo.Items.Add("========监听终止========");
            StartOrEnd(false);
        }

        private void StartOrEnd(bool IsStart)
        {
            if (IsStart)
            {
                btnStart.Enabled = false;
                chkIsAsync.Enabled = false;
                btnEnd.Enabled = true;
            }
            else
            {
                btnStart.Enabled = true;
                chkIsAsync.Enabled = true;
                btnEnd.Enabled = false;
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            listInfo.Items.Clear();
        }

        private void btnClinet_Click(object sender, EventArgs e)
        {
            sum++;
            Client client = new Client(sum);
            client.Show();
        }



        private void taskListener_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker task = (BackgroundWorker)sender;

                int receiveCount;
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, String.IsNullOrEmpty(txtPort.Text) ? 50000 : Convert.ToInt32(txtPort.Text));
                byte[] receiveData = new byte[1024];
                socket = null;
                if (radTCP.Checked)
                {
                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                else if (radUDP.Checked)
                {
                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                }
                socket.Bind(iep);

                IPEndPoint phone = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
                EndPoint remote = (EndPoint)(phone);//
                while (true)
                {
                    if (task.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    receiveData = new byte[1024];
                    receiveCount = socket.ReceiveFrom(receiveData, ref remote);
                    string result = Encoding.UTF8.GetString(receiveData, 0, receiveCount);
                    taskListener.ReportProgress(10, result);
                }
            }
            catch
            {

            }
        }

        private void taskListener_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 10)
            {
                listInfo.Items.Add(e.UserState);
                listInfo.SelectedIndex = listInfo.Items.Count - 1;
            }
        }

        private void taskListener_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }
    }
}
